package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.service.TestService;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2025-06-11 11:32
 */
@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 读
     *
     * @param id
     */
    @Override
    public void read(Long id) {
        //1.创建读写锁对象
        RReadWriteLock rwlock = redissonClient.getReadWriteLock("myLock:" + id);
        //2.获取读锁
        RLock lock = rwlock.readLock();
        lock.lock(5, TimeUnit.SECONDS);  //持有读锁期间，运行其他线程获取读锁，不允许获取写锁
        //3.指定读操作
        try {
            System.out.println("正在读数据..." + Thread.currentThread().getId());
        } finally {
            //4.释放读锁  故意-5s后自动释放
            //lock.unlock();
        }
    }

    @Override
    public void write(Long id) {
        //1.创建读写锁对象
        RReadWriteLock rwlock = redissonClient.getReadWriteLock("myLock:" + id);
        //2.获取写锁
        RLock lock = rwlock.writeLock();
        lock.lock(5, TimeUnit.SECONDS); //持有写锁期间，不允许获取读锁，不允许写锁
        //3.指定读操作
        try {
            System.out.println("正在写数据..." + Thread.currentThread().getId());
        } finally {
            //4.释放写锁  故意-5s后自动释放
            //lock.unlock();
        }
    }
}
